<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.type"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon :icon="item.icon" /> {{ item.title }}
        </a-button>
      </template>
      <template #djNo="{ record }">
        <a @click="handleForm({ id: record.id, djNo: record.djNo })">
          {{ record.djNo }}
        </a>
      </template>
    </BasicTable>
    <FormTabs @register="registerDrawer" @success="handleSuccess" @successPrint="handleSuccess1" />
    <PrintModal @register="registerPrintModal" />
    <Modal @register="registerPrint" @modifyfileName="fileNameXz" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8OrderFlowFhList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { m8OrderFlowFhDelete, m8OrderFlowFhSp } from '/@/api/m8/order/flow/fh/m8OrderFlowFh';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import FormTabs from './formTabs.vue';
  import { listSet, customListData } from '/@/api/test/testData';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import PrintModal from '/@/components/print/printModal.vue';
  import { useModal } from '/@/components/Modal';
  import Modal from './Modal.vue';
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerPrint, { openModal: openPrint }] = useModal();
  const { t } = useI18n('order.flow.fh.m8OrderFlowFh');
  const { showMessage, createConfirm } = useMessage();
  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});

  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('发货单管理'),
  };
  let title = ref('');
  const props = defineProps({
    type: { type: String, default: '' },
    viewCode: { type: String, default: 'list_layout' },
  });
  onMounted(async () => {
    const res = await listSet({ viewCode: props.viewCode });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);
    searchForm.value.schemas?.forEach((item) => {
      item.defaultValue = props[item.field];
      // if(item.field == 'type'){
      //   item.defaultValue = props.type
      // }
    });

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btn-addFH') {
        item.do = addFhHandle;
      } else if (item.btnKey === 'btn-addTH') {
        item.do = addFhHandleRed;
      } else if (item.btnKey === 'btn-SP') {
        item.do = spHandle;
      }
      if (item.btnKey == 'btnPrint') {
        item.do = () => handlePrint();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        params.url = listTabConfig.value.api;
        params.type = params.type ? params.type : props.type;
        return params;
      },
    });
    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => {
      actionColumnData.value.forEach((item) => {
        if (item.title == '删除') {
          item.popConfirm = {
            title: '是否确认删除数据',
            confirm: handleDelete.bind(this, { id: record.id }),
          };
          item.ifShow = record.allowDel;
        }
        if (item.title == '修改') {
          item.onClick = handleForm.bind(this, { id: record.id, djNo: record.djNo });
          //item.ifShow = record.allowEdit;
        }
      });
      return actionColumnData.value;
    },
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setProps, getSelectRowKeys, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await m8OrderFlowFhDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleSuccess() {
    reload();
  }

  function handleSuccess1(e) {
    reload();
    createConfirm({
      title: `保存审核已成功（${e}）`,
      content: `是否需要立即打印本条数据`,
      iconType: 'success',//info
      cancelText: '取消',
      okText: '确定',
      onOk: async () => {
        sucPrint(e)
      },
    });
  }
   // 保存审核后打印
   const sucPrint = (ids) => {
      let obj = {
        title: '发货明细打印',
        ids: ids,
        height: '0.7',
        width: '0.6',
        fileName: '',
      };
      // openPrintModal(true, obj);
      openPrint(true, obj);
  };


  const addFhHandle = () => {
    handleForm({ bred: '0' });
  };

  const addFhHandleRed = () => {
    let cusCodes = new Set();
    let cusCode = '';
    //判断是否同一供应商
    try {
      getSelectRows().forEach((item) => {
        cusCodes.add(item.djNo.cusCode);
        cusCode = item.djNo.cusCode;
        if (cusCodes.size > 1) {
          throw Error('请选择相同供应商的明细记录！');
        }
      });
    } catch (err: any) {
      showMessage(err.message);
      return;
    }
    let selKeys = getSelectRowKeys();
    let selIds = selKeys.join(',');
    console.log(cusCodes.values);
    handleForm({ selIds, bred: '1', cusCode });
  };

  const spHandle = async () => {
    let selKeys = getSelectRowKeys();
    let selIds = selKeys.join(',');
    if (selKeys.length > 0) {
      let params = {};
      let data = {
        selIds,
        ope: '4',
      };
      const res = await m8OrderFlowFhSp(params, data);
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！');
    }
  };

  // 打印
  const handlePrint = () => {
    let rows = getSelectRows();
    if (rows.length <= 0) {
      showMessage('请至少选择一条要打印的数据!');
    } else {
      let ids = '';
      rows.map((item) => {
        if (ids == '') {
          ids = item.id;
        } else {
          ids = ids + ',' + item.id;
        }
      });
      let obj = {
        title: '发货明细打印',
        ids: ids,
        height: '0.7',
        width: '0.6',
        fileName: '',
      };
      // openPrintModal(true, obj);
      openPrint(true, obj);
    }
  };
  function fileNameXz(data) {
    openPrintModal(true, data);
  }
</script>
